package com.beidu.lottery.call.mq.kafka;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.beidu.lottery.call.entity.MQMessageLog;
import com.beidu.lottery.call.entity.mq.ActivityBaseDTO;
import com.beidu.lottery.call.service.portal.MQMessageLogService;
import lombok.extern.slf4j.Slf4j;
import com.beidu.lottery.call.common.BaseContextHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * <p>
 * 基础消费类
 * </p>
 *
 * @author 北渡
 * @since 2024-08-30
 */
@Slf4j
@Component
public class ActivityBaseConsumer {

    @Resource
    private MQMessageLogService logService;

    /**
     * 设置用户信息上下文
     *
     * @param dto 活动基础DTO
     * @author 北渡
     */
    protected void setContext(ActivityBaseDTO dto) {
        BaseContextHandler.setUserId(dto.getUserId());
        BaseContextHandler.setTenant(dto.getTenantCode());
    }

    /**
     * 幂等校验
     *
     * @return true:重复, false:首次或有失败记录
     * @author 北渡
     */
    @SuppressWarnings({"all", "inverted"})
    protected boolean isIdempotent(String id) {
        return logService.count(Wrappers.lambdaQuery(MQMessageLog.class)
                .eq(MQMessageLog::getId, id).eq(MQMessageLog::getStatus, "1")) > 0;
    }

    /**
     * 重载saveOrUpdate方法
     *
     * @param topic     主题
     * @param data      数据
     * @param isSuccess 是否执行成功
     * @author 北渡
     */
    protected void saveOrUpdate(String topic, JSONObject data, boolean isSuccess) {
        logService.saveOrUpdate(topic, data, isSuccess);
    }

}
